﻿using FastMvc.Auth;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;

namespace FastMvc.Filters
{
    /// <summary>
    /// 检查权限用的Filter
    /// </summary>
    public class PermissionCheckFilter : IActionFilter
    {
        public void OnActionExecuting(ActionExecutingContext context)
        {
            // Action调用之前，进行Permission检查
            var controller = context.Controller as BaseController;
            if (controller == null)
            {
                return;
            }
            PermissionCheckAttribute cAttr = null;
            var cts= context.Controller.GetType().GetCustomAttributes(typeof(PermissionCheckAttribute), false);
            if (cts.Length > 0)
            {
                cAttr = cts[0] as PermissionCheckAttribute;
            }
            var ActionDes = context.ActionDescriptor as Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor;
            if (ActionDes != null)
            {
                PermissionCheckAttribute aAttr = null;
                var ats =ActionDes.MethodInfo.GetCustomAttributes(typeof(PermissionCheckAttribute), false);
                if (ats.Length > 0)
                {
                    aAttr = ats[0] as PermissionCheckAttribute;
                }

                if (aAttr != null || cAttr != null)
                {
                    var permission = "";
                    if (cAttr == null)
                    {
                        permission = aAttr.Permission;
                    }
                    else if (aAttr == null)
                    {
                        permission = cAttr.Permission;
                    }
                    else
                    {
                        permission = cAttr.Permission + "." + aAttr.Permission;
                    }
                    //UserAuth.Permissions ==null => 系统管理员？
                    if (!string.IsNullOrEmpty(permission))
                    {
                        var bc = context.Controller as BaseController;
                        if (bc.Permissions == null || bc.Permissions.Count() == 0)
                        {
                            if (!string.IsNullOrEmpty(bc.OrgId))
                                throw new FastMvc.Exceptions.UnAuthException("无权限的调用！");
                        }
                        else if(!bc.Permissions.Contains(permission))
                            throw new FastMvc.Exceptions.UnAuthException("无权限的调用！");
                    }
                }
            }
        }

        public void OnActionExecuted(ActionExecutedContext context)
        {
        }
    }
}
